package com.chinaedu.oc.serv.product.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinaedu.oc.bo.ProductQuery;
import com.chinaedu.oc.constant.Constant;
import com.chinaedu.oc.dao.product.ProductAreaDao;
import com.chinaedu.oc.dao.product.ProductDao;
import com.chinaedu.oc.dao.product.ProductDescDao;
import com.chinaedu.oc.dao.productline.ProductLineDao;
import com.chinaedu.oc.po.commodity.Commodity;
import com.chinaedu.oc.po.commodity.CommodityArea;
import com.chinaedu.oc.po.commodity.CommodityEducational;
import com.chinaedu.oc.po.commodity.CommodityGrade;
import com.chinaedu.oc.po.commodity.CommodityLevel;
import com.chinaedu.oc.po.commodity.CommodityProduct;
import com.chinaedu.oc.po.commodity.CommoditySaledepartment;
import com.chinaedu.oc.po.commodity.CommoditySpecialty;
import com.chinaedu.oc.po.dto.PubOutputDto;
import com.chinaedu.oc.po.product.Product;
import com.chinaedu.oc.po.product.ProductArea;
import com.chinaedu.oc.po.product.ProductDesc;
import com.chinaedu.oc.po.product.dto.AddProductInput;
import com.chinaedu.oc.po.product.dto.ProductInput;
import com.chinaedu.oc.po.product.dto.QueryProductInput;
import com.chinaedu.oc.po.product.dto.QueryProductOutput;
import com.chinaedu.oc.po.productline.ProductLine;
import com.chinaedu.oc.serv.commondity.ICommodityServ;
import com.chinaedu.oc.serv.product.IProduct;
import com.chinaedu.oc.util.common.CheckNull;
import com.chinaedu.oc.util.common.CheckParamException;
import com.chinaedu.oc.util.common.IdCreater;
import com.chinaedu.oc.util.common.JsonUtil;
import com.chinaedu.oc.util.common.StringUtil;
import com.chinaedu.oc.util.plugin.PageParams;
import com.chinaedu.oc.util.plugin.PageQueryResult;

@Service("IProduct")
public class IProductImpl implements IProduct {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	ProductDao productDao;
	@Autowired
	ProductDescDao productDescDao;
	@Autowired
	ProductAreaDao productAreaDao;
	@Autowired
	ProductLineDao productLineDao;
	@Autowired
	ICommodityServ iCommodityServ;

	/**
	 * 添加/更新产品
	 */
	@Override
	public PubOutputDto addProduct(AddProductInput input) throws CheckParamException {
		PubOutputDto out = new PubOutputDto();

		Product product = input.getProduct();

//		ProductLine pl = productLineDao.selectProductLineByCode(product.getProductLine());
//		if (pl == null) {
//			out.setStatus(Constant.FALSE);
//			out.setMsg("产品线不存在");
//
//			return out;
//		}
//		if ((Constant.STOP_USE_2 + "").equals(pl.getStartUse())) {
//			out.setMsg("产品线已停用");
//			out.setStatus(Constant.FALSE);
//
//			return out;
//		}

		// 根据产品的编码查询数据库，看数据是否存在
		QueryProductInput queryInput = new QueryProductInput();
		ProductQuery queryProduct = new ProductQuery();
		queryProduct.setCode(input.getProduct().getCode());
		queryInput.setProductQuery(queryProduct);
		QueryProductOutput qpo = this.queryProduct(queryInput);

		String productId = "";

		CheckNull ck = new CheckNull();
		ck.checkNull(product, "name", "businessType", "code", "productType", "billType", "unit");

		//换算有效期，把有效时长转换为有效期
		if(product.getExpiryDate() == null) {
			//如果有效期都是空，说明是长期有效，就不用设置
			if(!StringUtil.isBlack(product.getExpiryLength())) {
				int len = Integer.parseInt(product.getExpiryLength());
				product.setExpiryDate(new Timestamp(System.currentTimeMillis() + len*24*60*60*1000L));
			}
		}
		// 更新
		if (qpo.getListProduct().size() >= 1) {

			Product pOld = qpo.getListProduct().get(0);
			productId = pOld.getId();
			product.setId(productId);

			productDao.updateProductById(product);

			productAreaDao.deleteProductAreaByProductId(productId);
			productDescDao.deleteProductDescByProductId(productId);

		} else {
			// 添加
			productId = IdCreater.getId();
			// 添加product
			product.setUploadDate(new Timestamp(System.currentTimeMillis()));
			product.setEffStatus(Constant.YES_1);
			product.setId(productId);
			product.setReviewStatus(Constant.NO_2);

			productDao.insertProduct(product);	
		}

		// 添加地区
		List<ProductArea> listProductArea = input.getListProductArea();
		if (listProductArea != null && listProductArea.size() >= 1) {
			Iterator<ProductArea> it = listProductArea.iterator();
			while (it.hasNext()) {
				ProductArea p = it.next();
				if (StringUtil.isBlack(p.getAreaId())) {
					it.remove();
				} else {
					p.setProductId(productId);
					p.setId(IdCreater.getId());
				}
			}
			productAreaDao.insertProductAreaList(listProductArea);
		}
		// 添加产品描述
		List<ProductDesc> listProductDesc = input.getListProductDesc();
		if (listProductDesc != null && listProductDesc.size() >= 1) {
			Iterator<ProductDesc> it = listProductDesc.iterator();
			while (it.hasNext()) {
				ProductDesc p = it.next();

				p.setId(IdCreater.getId());
				p.setChangeDate(new Timestamp(System.currentTimeMillis()));
				p.setCreateDate(new Timestamp(System.currentTimeMillis()));
				p.setProductId(productId);
			}

			productDescDao.insertProductDescList(listProductDesc);
		}
		
		//更新则需要同步商品
		if (qpo.getListProduct().size() >= 1) {
			ProductInput tc = new ProductInput();
			tc.setToCommodityType(Constant.UPDATE);
			tc.setProductId(productId);
			this.toCommodity(tc);
		}

		out.setMsg("添加成功");
		out.setStatus(Constant.TRUE);
		return out;
	}

	/**
	 * 查询
	 */
	@Override
	public QueryProductOutput queryProduct(QueryProductInput input) {

		QueryProductOutput out = new QueryProductOutput();
		
		if(input == null) {
			out.setStatus(Constant.FALSE);
			out.setMsg("数据为空");
			return out;
		}
		if(input.getProductQuery() == null) {
			input.setProductQuery(new ProductQuery());
		}
		
		if (!StringUtil.isBlack(input.getProductQuery().getId())) {
			input.setLength(null);
			input.getProductQuery().setOrderName(null);
			input.getProductQuery().setOrderType(null);
			input.setStart(null);
		}
		//地区数据转换
		String area = input.getProductQuery().getAreas();
		String areas = "";
		if(!StringUtil.isBlack(area)) {
			String[] s = area.split(",");
			for(String ss : s) {
				areas += "'" + ss + "'" + ","; 
			}
			areas = areas.substring(0, areas.length()-1);
			input.getProductQuery().setAreas(areas);
		}else {
			input.getProductQuery().setAreas(null);
		}
		
		PageParams<Product> params = new PageParams<Product>();
		params.setPageParam(input.getStart(), input.getLength());
		params.setParam(input.getProductQuery());

		ProductQuery p = new ProductQuery();

		p = input.getProductQuery();
		p.setOrderName(input.getProductQuery().getOrderName());
		p.setOrderType(input.getProductQuery().getOrderType());

		params.setParam(p);

		// 查询product
		List<Product> list = productDao.selectProductByField(params);

		PageQueryResult r = params.getPageQueryResult();
		logger.debug("查询结果：{}", JsonUtil.toJson(r).toJSONString());

		out.setListProduct(list);
		out.setTotals(r.getTotal());
		out.setTotalPages(r.getTotalPage());

		// 查地区
		Map<String, List<ProductArea>> listProductArea = new HashMap<String, List<ProductArea>>();
		for (Product pp : list) {
			List<ProductArea> selectByProductId = productAreaDao.selectByProductId(pp.getId());
			listProductArea.put(pp.getId(), selectByProductId);
		}
		out.setListProductArea(listProductArea);

		// 查描述
		Map<String, List<ProductDesc>> listProductDesc = new HashMap<String, List<ProductDesc>>();
		for (Product pp : list) {
			List<ProductDesc> selectByProductId = productDescDao.selectByProductId(pp.getId());
			listProductDesc.put(pp.getId(), selectByProductId);
		}
		out.setListProductDesc(listProductDesc);

		out.setStatus(Constant.TRUE);
		return out;
	}

	/**
	 * 审核
	 */
	@Override
	public PubOutputDto reviewProduct(ProductInput input) {

		PubOutputDto out = new PubOutputDto();
		
		Product product = new Product();
		product.setId(input.getProductId());
		product.setReviewer(input.getUser());
		product.setReviewStatus(Constant.YES_1);
		product.setReviewDate(new Timestamp(System.currentTimeMillis()));
		int num = productDao.updateProductByField(product);
		if(num == 0) {
			out.setStatus(false);
			out.setMsg("产品不存在");
			return out;
		}
		out.setStatus(Constant.TRUE);

		return out;
	}

	/**
	 * 转化为商品
	 */
	@Override
	public PubOutputDto toCommodity(ProductInput input) {
		
		PubOutputDto out = new PubOutputDto();
		
		Product p = productDao.selectProductById(input.getProductId());
		List<ProductArea> listA = productAreaDao.selectByProductId(input.getProductId());
		if(p == null) {
			out.setStatus(Constant.FALSE);
			out.setMsg("产品不存在");
			return out;
		}
		if(Constant.NO_2.equals(p.getReviewStatus())) {
			out.setStatus(Constant.FALSE);
			out.setMsg("请审核后再推送");
			return out;
		}
		
		
		Commodity commodity = new Commodity();
		commodity.setBusinessType(p.getBusinessType());
		commodity.setCommodityName(p.getName());
		
		CommodityProduct commodityProduct = new CommodityProduct();
		commodityProduct.setProductId(p.getId());
		commodityProduct.setProductSource(p.getProductLine());
		commodity.setCommodityProduct(commodityProduct);
		
		// 和销售部门关联
		List<CommoditySaledepartment> saledepartments = new ArrayList<CommoditySaledepartment>();
		CommoditySaledepartment saledepartment = new CommoditySaledepartment();
		saledepartment.setSaleDepartmentId(p.getDepartment());   //销售部门ID
		saledepartments.add(saledepartment);
		commodity.setCommoditySaledepartments(saledepartments);
		
		// 添加和学段的关系
		List<CommodityLevel> commodityLevels = new ArrayList<CommodityLevel>();
		CommodityLevel commodityLevel = new CommodityLevel();
		commodityLevel.setLevelId(p.getSchoolLevel());  //学段ID
		commodityLevels.add(commodityLevel);
		commodity.setCommodityLevels(commodityLevels);
		
		// 添加和学科的关系
		List<CommoditySpecialty> commoditySpecialties = new ArrayList<CommoditySpecialty>();
		CommoditySpecialty commoditySpecialty = new CommoditySpecialty();
		commoditySpecialty.setSpecialtyId(p.getSpecialty());   //学科ID
		commoditySpecialties.add(commoditySpecialty);
		commodity.setCommoditySpecialty(commoditySpecialties);
		
		// 添加和年级的关系
		List<CommodityGrade> commodityGrades = new ArrayList<CommodityGrade>();
		CommodityGrade commodityGrade = new CommodityGrade();
		commodityGrade.setGradeId(p.getGrade());  //年级ID
		commodityGrades.add(commodityGrade);
		commodity.setCommodityGrade(commodityGrades);
		
		// 添加和学制类型的关系
		List<CommodityEducational> commodityEducationals = new ArrayList<CommodityEducational>();
		CommodityEducational commodityEducational = new CommodityEducational();
		commodityEducational.setEducationalId(p.getSchoolSystem());
		commodityEducationals.add(commodityEducational);
		commodity.setCommodityEducational(commodityEducationals);
		
		commodity.setCreatorId(input.getUser());
		
		//地区
		if(listA != null && listA.size()>=1) {
			List<CommodityArea> commodityAreas = new ArrayList<CommodityArea>();
			for(ProductArea pa : listA) {
				CommodityArea a = new CommodityArea();
				a.setAreaId(pa.getAreaId());
				
				commodityAreas.add(a);
			}
			commodity.setCommodityAreas(commodityAreas );
		}
		
		commodity.setInsertOrUpdate(input.getToCommodityType());
		
		try {
			iCommodityServ.synchronizeCommodityOrUpdate(commodity);
		} catch (Exception e) {
			e.printStackTrace();
			out.setStatus(Constant.FALSE);
			out.setMsg("推送失败");
			return out;
		}
		
		
		out.setStatus(Constant.TRUE);
		return out;
	}

}
